<template>
  <div class="filter-container">
    <div class="card filter" v-show="isCollapse">
      <h4 v-if="title" class="title sle">
        {{ title }}
      </h4>
      <el-input v-model="filterUiTestText"
                :placeholder='$t("interface.EnterModuleNameForFiltering")' clearable/>

      <el-scrollbar :style="{ height: title ? `calc(100% - 95px)` : `calc(100% - 56px)` }">
        <!--      <el-button v-if="interfaceCatTree" style="width: 100%">添加模块</el-button>-->
        <el-tree
            ref="treeRef"
            class="filter-tree"
            :data="uiTestCatTree"
            @node-click="uiTestCatNodeClick"
            :expand-on-click-node="false"
            node-key="id"
            :default-expanded-keys="defaultExpandedKeys"
            @node-expand="uiTestCatNodeExpand"
            @node-collapse="uiTestCatNodeCollapse"
            :filter-node-method="filterUiTestCat"

            draggable
            @node-drop="handleDrop"
        >
          <template #empty>
            <el-button style="width: 100%" @click="appendChildrenCat({id:'',label:''})">新增模块</el-button>
          </template>
          <template #default="{ node, data }">

            <span class="custom-tree-node">
<!--              模块图标-->
              <!--              <span ><el-icon><Folder/></el-icon></span>-->
              <span v-show="!defaultExpandedKeys.some(ele =>ele === data.id)"><el-icon><Folder/></el-icon></span>
              <span v-show="defaultExpandedKeys.some(ele => ele === data.id)"><el-icon><FolderOpened/></el-icon></span>
              <!--              显示文本-->
              <span class="node_title">{{ node.label }}</span>
              <!--              显示编辑框-->
<!--              <span v-show="node.data.is_edit" class="node_title">-->
<!--                <el-input :id="'id' + node.data.id" v-model="data.label" size="small"></el-input>-->
<!--              </span>-->
              <!--              <span class="count_title"><span style="color: #0000cc">3</span></span>-->

              <!--              显示按钮-->
              <span class="node-operate child" @click.stop>
                <el-icon color="green"
                         v-show="node.data.id === selectedUiTestCatId">
                  <Location></Location>
                </el-icon>

                <el-dropdown trigger="click">
                  <el-icon><MoreFilled/></el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :icon="CirclePlus"
                                        @click="addInterfaceToSourceList(node.data.id)">新增接口</el-dropdown-item>
                      <el-dropdown-item :icon="CirclePlus">新增同级模块</el-dropdown-item>
                      <el-dropdown-item :icon="CirclePlus"
                                        @click="appendChildrenCat({id:node.data.id,label:data.label})">新增子模块</el-dropdown-item>
                      <el-dropdown-item :icon="Edit">编辑</el-dropdown-item>
                      <el-dropdown-item :icon="Delete">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>

              </span>

            </span>
          </template>
        </el-tree>

      </el-scrollbar>

<!--      新增模块-->
      <UiTestCatDialog
          @clearSearch="clearSearch"
          ref="UiTestCatDialogRef">
      </UiTestCatDialog>
    </div>
    <div :class="['collapse-btn',isCollapse?'collapse-btn-collapse':'collapse-btn-close']"
         @click="isCollapse=!isCollapse">
      <el-icon>
        <ArrowLeft v-show="isCollapse"></ArrowLeft>
        <ArrowRight v-show="!isCollapse"></ArrowRight>
      </el-icon>
    </div>
  </div>

</template>

<script setup name="interfaceTabs">

import {CirclePlus, Delete, Edit, FolderOpened, Folder, MoreFilled, Location} from "@element-plus/icons-vue";
import {ElTree} from "element-plus";
import {nextTick, onBeforeUnmount, onMounted, ref, watch} from "vue";
import {storeToRefs} from "pinia";
import UiTestCatDialog from './uiTestCatDialog.vue'
import {useUiTestStore} from "@/stores/modules/ui/uitest.js";
import {useProjectStore} from "@/stores/modules/project/project.js";
import {getGuidApi} from "@/api/modules/system/common.js";

const uiTestStore = useUiTestStore()
const projectStore = useProjectStore()

const {
  uiTestCatTree,
  selectedUiTestCatName,
  selectedUiTestCatId,
} = storeToRefs(uiTestStore)
const {currentProject, currentProjectId} = storeToRefs(projectStore)

const isCollapse = ref(true)

onMounted(() => {
  uiTestStore.getUiTestCatTree()
})


const title = ref("")
const filterUiTestText = ref("")
const treeRef = ref()

// 清空搜索（当新增成功或删除成功后，重新获取数据，需要清空该过滤树）
const clearSearch = (val) => {
  filterUiTestText.value = ""
}

// 过滤函数
watch(filterUiTestText, (val) => {
  treeRef.value.filter(val)
})
const filterUiTestCat = (value, data) => {
  if (!value) return true
  return data.label.includes(value)
}

const handleDrop = (draggingNode, dropNode, dropType, ev) => {
  // draggingNode 正在拖动的节点
  // dropNode 相对的节点
  // dropType拖动类型，对于相对节点而言(before、after、inner)
  // ev 拖动事件

  console.log( "拖动：" + draggingNode.label)
  console.log( dropType)
  console.log( dropNode.label)
}


// 默认展开的模块Keys
const defaultExpandedKeys = ref(["1758059113725964288"])

// 节点被展开时时，触发
const uiTestCatNodeExpand = (data, node, TreeNode) => {
// 共三个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、节点对应的 Node、节点组件本身
  defaultExpandedKeys.value.push(data.id)
}

// 节点被关闭时，触发
const uiTestCatNodeCollapse = (data, node, TreeNode) => {
// 共三个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、节点对应的 Node、节点组件本身
  let dataIndex = defaultExpandedKeys.value.indexOf(data.id)
  if (dataIndex !== -1) {
    defaultExpandedKeys.value.splice(dataIndex, 1)
  }
}


// 点击分类名，查询该分类下的接口
const uiTestCatNodeClick = (data, node, TreeNode, event) => {
  // 三个参数：对应于节点点击的节点对象，TreeNode 的 node 属性, TreeNode和事件对象
  selectedUiTestCatName.value = data.label
  selectedUiTestCatId.value = data.id

  // 模块点击事件，供列表查询，刷新数据
  $eventBus.emit('uiTestCatNodeClick')

}

// 新增接口
const addInterfaceToSourceList = async (catId) => {
  await getGuidApi().then(res => {

    // 添加一个初始化的接口资源
    // interfaceStore.addInitInterfaceSource(catId)

  })
}


const UiTestCatDialogRef = ref()
// 添加子节点
const appendChildrenCat = (uiTestCat = undefined) => {
  UiTestCatDialogRef.value.showUiTestCatFrom('create', uiTestCat)
  // let newChildId = ""
  // getGuidApi().then(res => {
  //   newChildId = res.data
  //   // 获取父级节点
  //   const parent = node.parent
  //   // 添加新的节点
  //   const newChild = {id: newChildId, label: "",is_edit:true, parentId: parent.data.id, project: currentProjectId, children: []}
  //   if (!data.children) {
  //     data.children = []
  //   }
  //   data.children.push(newChild)
  //   // 将添加的节点添加到展开列表中，即点击后，就展开子节点
  //   defaultExpandedKeys.value.push(newChildId)
  //   // 焦点到新增的子节点上
  //   nextTick(()=>{
  //     document.querySelector("#id" + newChildId).focus()
  //     console.log(document.querySelector("#id" + newChildId))
  //   })
  // })
}

// 删除节点
// const remove = (node, data) => {
//   const parent = node.parent
//   const children = parent.data.children || parent.data
//   const index = children.findIndex((d) => d.id === data.id)
//   children.splice(index, 1)
//   dataSource.value = [...dataSource.value]
// }

// 切换项目时，重新查询模块分类树
onMounted(() => {
  $eventBus.on("updateCurrentProject", async () => {
    await uiTestStore.getUiTestCatTree()
    // defaultExpandedKeys.value = []
  })
})
onBeforeUnmount(() => {
  $eventBus.off("updateCurrentProject")
})


</script>

<style lang="scss">
@import "index.scss";
</style>
